//
//  SelectPassengersController.swift
//  AirTravel
//
//  Created by apple on 2021/8/13.
//

import UIKit
import Moya
import SwiftyJSON

protocol SelectPassengersDelegate:NSObjectProtocol {
    func selectPassengersClick(array:[Dictionary<String,Any>])
}

class SelectPassengersController: UIViewController {

    @IBOutlet weak var toplabel: UILabel!
    @IBOutlet weak var topBt: UIButton!
    @IBOutlet weak var submitBtn: UIButton!
    @IBOutlet weak var tabView: UITableView!
    @IBOutlet weak var topView: UIView!
    weak var delegate: SelectPassengersDelegate?
    let identifySP = "SelectPassengersCell"
    /// 用来主动取消网络请求
    var cancelableRequest: Cancellable?
    var dataSouce : Array<Any>?
    var identity_type = ""
    var mutArray = [Dictionary<String,Any>]()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = false
        self.navigationController?.navigationBar.tintColor = UIColor.black
        self.navigationController?.navigationBar.titleTextAttributes = [
            NSAttributedString.Key.foregroundColor : UIColor.black]
        self.gitIdCardList()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.navigationBar.tintColor = UIColor.white
        self.navigationController?.navigationBar.titleTextAttributes = [
            NSAttributedString.Key.foregroundColor : UIColor.white]
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        
        
        self.title = "选择乘客"
        
        if(identity_type == "10"){
            self.title = "选择入住人"
            toplabel.text = "新增入住人"
//            self.topBt.setTitle("新增入住人", for: .normal)
        }
        self.topView.layer.cornerRadius = 6
        self.topView.layer.masksToBounds = true
        self.submitBtn.layer.cornerRadius = 6
        self.submitBtn.layer.masksToBounds = true
        
        self.tabView.dataSource = self
        self.tabView.delegate = self
        self.tabView.rowHeight = 72
        self.tabView.tableFooterView = UIView.init()
        self.tabView.register(UINib.init(nibName: "SelectPassengersCell", bundle: nil), forCellReuseIdentifier: identifySP)
        self.tabView.ly_emptyView = LYEmptyView.empty(withImageStr: "无数据、空数据", titleStr: "", detailStr: "暂无任何内容~")
    }
    
    //获取用户身份证信息
    func gitIdCardList() {
        cancelableRequest = NetWorkRequest(API1.gitIdCardList, completion: {[weak self] (responseString) -> (Void) in
            let list = responseString["data"].arrayObject
            if let array = list {
                self?.dataSouce = array
                if self?.mutArray.count == 0 {
                    for _ in array {
                        self?.mutArray.append([:])
                    }
                }
            }
            self?.tabView.reloadData()
        }, failed: { (failedResutl) -> (Void) in
            print("服务器返回code不为0000啦~\(failedResutl)")
        }, errorResult: { () -> (Void) in
            print("网络异常")
        })
    }

    //新增
    @IBAction func add(_ sender: Any) {
        let vc = EditPassengersController()
        if(identity_type == "10"){
            vc.tag = 1
        }
        vc.is_editor = false
        vc.identity_type = self.identity_type
        self.navigationController?.pushViewController(vc, animated: true)
    }
    //确定
    @IBAction func submit(_ sender: Any) {
        if self.mutArray.count > 0 {
            self.navigationController?.popViewController(animated: true)
        }
    }
}

extension SelectPassengersController:UITableViewDataSource,UITableViewDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSouce?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: identifySP) as! SelectPassengersCell
        cell.selectionStyle = .none
        cell.modifyBtn.tag = indexPath.row
        cell.modifyBtn.addTarget(self, action: #selector(modify(sender:)), for: .touchUpInside)
        cell.chooseBtn.tag = indexPath.row
        cell.chooseBtn.addTarget(self, action: #selector(choose(sender:)), for: .touchUpInside)
        
        if let array = self.dataSouce {
            if array.count > self.mutArray.count {
                self.mutArray.append([:])
            }
            let dic = array[indexPath.row] as? Dictionary<String,Any>
            cell.nameLab.text = "\(dic?["name"] ?? "")"
            let identity_type = "\(dic?["identity_type"] ?? "")"
            switch identity_type {
            case "1":
                cell.tagLab.text = "成人票"
            case "2":
                cell.tagLab.text = "儿童票"
            case "3":
                cell.tagLab.text = "学生票"
            case "4":
                cell.tagLab.text = "残/军票"
            default:
                cell.tagLab.text = ""
            }
            let doument_type = "\(dic?["doument_type"] ?? "")"
            switch doument_type {
            case "1":
                cell.idCardLab.text = "身份证 \(dic?["idcard"] ?? "")"
            case "2":
                cell.idCardLab.text = "护照 \(dic?["idcard"] ?? "")"
            case "3":
                cell.idCardLab.text = "军人证 \(dic?["idcard"] ?? "")"
            case "4":
                cell.idCardLab.text = "回乡证 \(dic?["idcard"] ?? "")"
            case "5":
                cell.idCardLab.text = "台胞证 \(dic?["idcard"] ?? "")"
            case "6":
                cell.idCardLab.text = "外国人永久居留证 \(dic?["idcard"] ?? "")"
            case "99":
                cell.idCardLab.text = "其他 \(dic?["idcard"] ?? "")"
            default:
                cell.idCardLab.text = ""
            }
            
            if(identity_type == "10"){
                cell.idCardLab.isHidden = true
            }
            
            let i = self.mutArray[indexPath.row]
            if i.isEmpty {
                cell.chooseBtn.isSelected = false
            }else{
                cell.chooseBtn.isSelected = true
            }
        }
        return cell
    }
    
    @objc func modify(sender:UIButton) {
        if let array = self.dataSouce {
            let dic = array[sender.tag] as? Dictionary<String,Any>
            let vc = EditPassengersController()
            vc.delegate = self
            vc.is_editor = true
            vc.identity_type = self.identity_type
            vc.dataDic = dic
            vc.number = sender.tag
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    //选择
    @objc func choose(sender:UIButton) {
        if let array = self.dataSouce {
            let dic = array[sender.tag] as? Dictionary<String,Any>
            let i = self.mutArray[sender.tag]
            if i.isEmpty {
                self.mutArray[sender.tag] = dic ?? [:]
            }else{
                self.mutArray[sender.tag] = [:]
            }
            self.delegate?.selectPassengersClick(array: mutArray)
        }
        self.tabView.reloadData()
    }
    
}

extension SelectPassengersController:EditPassengersDelegate{
    func editPassengersClick(number: Int) {
        self.mutArray.remove(at: number)
        self.delegate?.selectPassengersClick(array: mutArray)
    }
    
    func addPassengersClick(type: Int) {
        self.mutArray.append([:])
        self.delegate?.selectPassengersClick(array: mutArray)
    }
    
    
}
